package com.example.RemindMe;


import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.*;


public class NoteActivity extends ListActivity
{
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private NotesDbAdapter mDbHelper;
    private SharedPreferences sharedPreferences;
    private static String sharedPrefName="sharedPrefName";

    SimpleCursorAdapter notes;
    Context ctx;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ctx = this;
        DialogActivity.noteActvityStarted=true;
        setContentView(R.layout.notepad_list);
        
        ListView myList = (ListView) findViewById(R.layout.notepad_list);

        //load SharedPref
        sharedPreferences = getSharedPreferences(sharedPrefName, MODE_PRIVATE);
        Boolean sharedBoolean = sharedPreferences.getBoolean("sharedBoolean", false);

        //Don't show Overlay(visual hints) if sharedBoolean == true
        if (sharedBoolean == false){

            //save  SharedPref
            sharedPreferences = getSharedPreferences(sharedPrefName, MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("sharedBoolean", true);
            editor.commit();
            showOverLay();
        }

        mDbHelper = new NotesDbAdapter(this);
        mDbHelper.open();
        fillData();

        //pop-up Menü(context menu) erscheint wenn man auf ein ListView-Item länger klickt
        registerForContextMenu(getListView());
    }

    private void fillData() {

        Cursor notesCursor = mDbHelper.fetchAllNotes();

        //Alle Zeilen von der Datenbank holen
        notesCursor = mDbHelper.fetchAllNotes();
        startManagingCursor(notesCursor);

        //Array erstellen und Spalten der Tabelle auswählen, welche angezeigt werden sollen
        String[] from = new String[]{NotesDbAdapter.KEY_TITLE, NotesDbAdapter.KEY_BODY};

        //Felder mit Layout-XML-Felder verknüpfen
        int[] to = new int[]{R.id.text11, R.id.text2};

        // Now create a simple cursor adapter and set it to display
         notes =new SimpleCursorAdapter(this, R.layout.custom_row_view, notesCursor, from, to);
        setListAdapter(notes);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID,0, R.string.menu_insert);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {

        switch(item.getItemId()) {
            case INSERT_ID:
                createNote();
                return true;
        }

        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);

        menu.add(0,DELETE_ID,0,R.string.menu_delete);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {

        switch (item.getItemId()){
            case DELETE_ID:
                AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
                mDbHelper.deleteNote(info.id);
                fillData();
                Toast.makeText(this,"Note deleted",Toast.LENGTH_SHORT).show();
                return true;
        }
        return super.onContextItemSelected(item);
    }

    private void createNote() {
        Intent intent = new Intent(this, NoteEdit.class);
        startActivityForResult(intent, ACTIVITY_CREATE);


    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        super.onListItemClick(l, v, position, id);
        Intent i = new Intent(this, NoteEdit.class);
        i.putExtra(NotesDbAdapter.KEY_ROWID, id);
        startActivityForResult(i, ACTIVITY_EDIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        fillData();

    }

    private void showOverLay(){

        final Dialog dialog = new Dialog(ctx, android.R.style.Theme_Translucent_NoTitleBar);
        dialog.setContentView(R.layout.overlay_view);
        RelativeLayout layout = (RelativeLayout) dialog.findViewById(R.id.overlayLayout);
        layout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                dialog.dismiss();
            }
        });
        dialog.show();

    }
 
    //When app is sent to background(when home button clicked) finish the note-activity, retype password
    @Override
	protected void onUserLeaveHint() {
		super.onUserLeaveHint();
		DialogActivity.noteActvityStarted=false;
		finish();
	}

	//------------------------------------------------Action Bar Methods -----------------------------------------------
    public void onClickHome (View v)
    {
        goHome (this);
    }

    /**
     * Handle the click on the search button.
     *
     * @param v View
     * @return void
     */

    public void onClickSearch (View v)
    {
        startActivity (new Intent(getApplicationContext(), SearchActivity.class));
        finish();
    }

    /**
     * Handle the click on the About button.
     *
     * @param v View
     * @return void
     */

    public void onClickAbout (View v)
    {
        startActivity (new Intent(getApplicationContext(), AboutActivity.class));
        finish();
    }

    /**
     * Handle the click of a Feature button.
     *
     * @param v View
     * @return void
     */
    /**
     * Go back to the home activity.
     *
     * @param context Context
     * @return void
     */

    public void goHome(Context context)
    {
        final Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity (intent);
        finish();
    }

    /**
     * Use the activity label to set the text in the activity's title text view.
     * The argument gives the name of the view.
     *
     * <p> This method is needed because we have a custom title bar rather than the default Android title bar.
     * See the theme definitons in styles.xml.
     *
     * @param textViewId int
     * @return void
     */

    public void setTitleFromActivityLabel (int textViewId)
    {
        TextView tv = (TextView) findViewById (textViewId);
        if (tv != null) tv.setText (getTitle ());
    } // end setTitleText

    /**
     * Show a string on the screen via Toast.
     *
     * @param msg String
     * @return void
     */

    public void toast (String msg)
    {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show ();
    } // end toast

    /**
     * Send a message to the debug log and display it using Toast.
     */
    public void trace (String msg)
    {
        Log.d("Demo", msg);
        toast (msg);
    }

}
